/**
 * 全局数据配置
 */
const data = {
	isInit: false,
	looptime: 0,
	currentTime: 1,
	lastData: 0,
	buffSize: [],
	oneTimeData: 0,
	printNum: [],
	printerNum: 1,
	currentPrint: 1,

	//蓝牙信息
	BLEInformation: {},
}

const SUCCESS = {
	code: 0
}
const ERROR = function error(msg) {
	return {
		code: 1,
		msg: msg
	}
}

/**
 * 初始化
 */
function init() {
	var list = []
	var numList = []
	var j = 0
	for (var i = 20; i < 200; i += 10) {
		list[j] = i;
		j++
	}
	for (var i = 1; i < 10; i++) {
		numList[i - 1] = i
	}
	setData({
		buffSize: list,
		oneTimeData: list[0],
		printNum: numList,
		printerNum: numList[0]
	})
}

function setData(data0) {
	for (let key in data0) {
		data[key] = data0[key];
	};
}

/**
 * 准备发送，根据每次发送字节数来处理分包数量
 * @param {Object} buff 发送字节
 * @param {Object} BLEInformation 蓝牙信息
 */
export function tablePrepareSend(buff, BLEInformation, fun) {
	if (!buff || !BLEInformation) {
		console.error("tablePrepareSend 数据入参错误！！！");
		fun(ERROR("发送打印标签，数据入参错误"));
		return null;
	}
	if (!data.isInit) {
		init();
	}
	data.BLEInformation = BLEInformation; //蓝牙连接信息

	var time = data.oneTimeData;
	var looptime = parseInt(buff.length / time);
	var lastData = parseInt(buff.length % time);
	setData({
		looptime: looptime + 1,
		lastData: lastData,
		currentTime: 1,
	})
	send(buff, fun);
}

/**
 * 分包发送
 * @param {Object} buff
 */
function send(buff, fun) { //分包发送
	var currentTime = data.currentTime
	var loopTime = data.looptime
	var lastData = data.lastData
	var onTimeData = data.oneTimeData
	var printNum = data.printerNum
	var currentPrint = data.currentPrint
	var buf
	var dataView
	if (currentTime < loopTime) {
		buf = new ArrayBuffer(onTimeData)
		dataView = new DataView(buf)
		for (var i = 0; i < onTimeData; ++i) {
			dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
		}
	} else {
		buf = new ArrayBuffer(lastData)
		dataView = new DataView(buf)
		for (var i = 0; i < lastData; ++i) {
			dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
		}
	}
	//console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
	uni.writeBLECharacteristicValue({
		deviceId: data.BLEInformation.deviceId,
		serviceId: data.BLEInformation.writeServiceId,
		characteristicId: data.BLEInformation.writeCharaterId,
		value: buf,
		success: function(res) {
			fun(SUCCESS, {
				currentPrintNum: currentTime, //当前发送完成包（执行中任务）
				totalPrintNum: loopTime, //当前发送总包数（执行中任务）
			});
		},
		fail: function(e) {
			console.log(e);
			fun(ERROR('传输第' + currentTime + '包数据失败'))
		},
		complete: function() {
			currentTime++
			if (currentTime <= loopTime) {
				setData({
					currentTime: currentTime
				})
				send(buff, fun)
			} else {
				if (currentPrint == printNum) {
					setData({
						looptime: 0,
						lastData: 0,
						currentTime: 1,
						isLabelSend: false,
						currentPrint: 1
					})
				} else {
					currentPrint++
					setData({
						currentPrint: currentPrint,
						currentTime: 1,
					})
					send(buff, fun)
				}
			}
		}
	})
};